package com.oscar.web.controller;


import com.oscar.web.domain.*;
import com.oscar.web.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.sql.Date;
import java.util.List;

/**
 * 后台控制站，接收模板传来的数据，向模板传输数据
 */
@Controller  //Controller用来表示Spring某个类的是否可以接收HTTP请求
public class BookController {

    //从service层获取挖掘到的数据进行清洗
    @Autowired
    private BookService bookService ;

    @Autowired
    private UsersService usersService ;

    @Autowired
    private UserBookEvaluateService userBookEvaluateService ;

    @Autowired
    private UserBookBuyService userBookBuyService;

    @Autowired
    private UserBookCollectService userBookCollectService;

    @Autowired
    private RecommenderService recommenderService;

    //获取近期热门推荐
    @RequestMapping(value={"/","/index/recenthot"})
    public ModelAndView getRecentHotBooks(){
        ModelAndView mv = new ModelAndView("index") ;
        List<Book> list = recommenderService.getHotRecommendations(0);
        mv.addObject("list",list);
        return mv;
    }

    //高分图书推荐
    @RequestMapping("/index/goodbooks")
    public ModelAndView getGoodBooks(){
        ModelAndView mv = new ModelAndView("goodbooks") ;
        List<Book> list = recommenderService.getGoodRecommendations(0);
        mv.addObject("list",list);
        return mv;
    }


   //图书搜索操作
    @RequestMapping("/books/searchBook")
    //RequestMapping表示所有到/books/searchBook的请求会由search方法处理
    public ModelAndView search(String findName ,
                               Integer pageNumber ,
                               HttpServletRequest request) {

        if(pageNumber == null)pageNumber = 0 ;
        Page<Book> page = bookService.search(findName ,pageNumber ,20) ;

        //通过ModelAndView("searchResult")构造方法可以指定返回到searchResult.ftl页面，也可以通过setViewName()方法跳转到指定的页面
        ModelAndView mv = new ModelAndView("searchResult") ;
        //将数据page值取名为page传到前端模板页面，让Freemarker模板引擎用于结合展现
        mv.addObject("page",page) ;
        //使用addObject()设置需要返回的值，addObject()有几个不同参数的方法，可以默认和指定返回对象的名字。
        mv.addObject("findName",findName) ;

        return mv;
    }

    //图书详情页
    @RequestMapping("/books/details")
    public ModelAndView showDetails(int bookid){
        Book book = bookService.findById(bookid) ;
        ModelAndView mv = new ModelAndView("detail") ;
//        String imageUrl=book.getImageUrl().substring(6);
//        String imageUrl=book.getImageUrl().replaceFirst("s","");
        String imageUrl=book.getImageUrl().split("\\?v=")[0];
        System.out.println("==============>>"+imageUrl);
        List<Book> list = recommenderService.ItemCFRecommendations(bookid);
        mv.addObject("book",book);
        mv.addObject("imageUrl",imageUrl);
        mv.addObject("list",list);
        mv.addObject("num",0);
        return mv;
    }


    /**
     * 收藏操作
     * @param bookid 发送/books/collect请求的前端传来的图书id
     * @param request 发送/books/collect请求的前端传来的获取对象信息
     * @return collectMsg.ftl 视图页面
     */
    @RequestMapping("/books/collect")
    public ModelAndView collect(int bookid , HttpServletRequest request){
        //request.getUserPrincipal() 获取请求的用户的信息
        String username = request.getUserPrincipal().getName() ;
        Users user = usersService.findByUsername(username) ;

        collect c=new collect();//新建一个collect对象
        c.setUserId(user.getUserId());
        c.setBookId(bookid);
        c.setTimestamp((int) (System.currentTimeMillis()/1000));

        ModelAndView mv = new ModelAndView("collectMsg") ;
        String msg = "" ;
        try {//try-catch进行捕获异常消息
                msg=userBookCollectService.collectBook(c);//把收藏下消息传到server层进行处理
        }catch (Exception e){//捕获巡行超时异常
            msg = "数据走丢了，请稍后再试。。。" ;//反回异常消息
        }

        mv.addObject("bookid",bookid) ;
        mv.addObject("msg",msg);

        return mv;
    }

    /**
     * 购买操作
     * @param bookid 发送/books/buy请求的前端传来的图书id
     * @param request 发送/books/buy请求的前端传来的获取对象信息
     * @return  buyMsg.ftl 视图页面
     */
    @RequestMapping("/books/buy")
    public ModelAndView buy(int bookid , HttpServletRequest request){
        //request.getUserPrincipal() 获取请求的用户的信息
        String username = request.getUserPrincipal().getName() ;
        Users user = usersService.findByUsername(username) ;

        buy b=new buy();//新建一个buy对象
        b.setUserId(user.getUserId());
        b.setBookId(bookid);
        b.setTimestamp((int)(System.currentTimeMillis()/1000));

        ModelAndView mv = new ModelAndView("buyMsg") ;
        String msg = "感谢您的购买，期待您的下一次购买！";
        try {//try-catch进行捕获异常消息
            userBookBuyService.buyBook(b);//把购买下消息传到server层进行处理
        }catch (Exception e){//捕获巡行超时异常
            msg = "数据走丢了，请稍后再试。。。" ;//反回异常消息
        }
        mv.addObject("bookid",bookid) ;
        mv.addObject("msg",msg);
        return mv;
    }

    /**
     * 进入评价页面
     * @param bookid 发送/books/to_eva请求的前端传来的图书id
     * @return evaluate.ftl  视图页面
     */
    @RequestMapping("/books/to_eva")//进入评价页面
    public ModelAndView toEvalute(int bookid ){
        Book book = bookService.findById(bookid);
        ModelAndView mv = new ModelAndView("evaluate") ;
        mv.addObject("book",book) ;
        return mv;
    }

    /**
     * 评价操作
     * @param bookid 发送/books/evaluate请求的前端传来的图书id
     * @param score 发送/books/evaluate请求的前端传来的打分
     * @param request 发送/books/evaluate请求的前端传来的获取对象信息
     * @return evaluateMsg.ftl 视图页面
     */
    @RequestMapping("/books/evaluate") // 进行评价操作
    public ModelAndView evaluate(int bookid ,Integer score ,HttpServletRequest request ){
        String username = request.getUserPrincipal().getName() ;//从前端获取用户id
        Users user = usersService.findByUsername(username) ;//从后端获取用信息

        System.out.println("创建一个用户对象");
        rating r = new rating() ; //新建一个用户操作对象
        r.setBookId(bookid);//给操作对象属性赋值  userid,bookid,bookvalue,timestamp
        r.setUserId(user.getUserId());
        r.setScore(score);
        r.setTimestamp((int)(System.currentTimeMillis()/1000));

        ModelAndView mv = new ModelAndView("evaluateMsg") ;//新建一个评价视图容器
        String msg = "";//设置信息初始值
        try {//try-catch进行捕获异常消息
            System.out.println("开始进行图书评价。。。。。。");
            msg=userBookEvaluateService.saveValue(r);//把评价下消息传到server层进行处理
        }catch (Exception e){//捕获巡行超时异常
            msg = "数据走丢了，请稍后再试。。。" ;//反回异常消息
        }
        mv.addObject("msg",msg);//将捕获的异常消息存入容器中
        mv.addObject("bookid",bookid) ;//将获取的图书数据村容容器中
        return mv;//返回评价视图容器
    }

}
